import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Toaster } from '@/components/ui/sonner';
import { Tabs, TabsContent } from '@/components/ui/tabs';
import config, { OpenTemuDialogMessage, PostMessageType } from '@/config';
import { useTemuStore } from '@/store/temu';
import AvaliableSynchronization from './AvaliableSynchronization';
import OperationType, { temuOperationList } from './OperationType';
import TemuSetting from './TemuSetting';
import { Button } from '@/components/ui/button';
import { setProxyDirect } from '@/lib/proxy';
import { useProxyStore } from '@/store/proxy';
import { useProxy } from '../hook/useProxy';
import RegidtrationActivity from './RegidtrationActivity';
function App() {
  const [open, setOpen] = useState(false);
  const currentTabValue = useTemuStore((state) => state.currentTabValue);
  const proxyDispatch = useProxyStore((state) => state.dispatch);
  const currentProxy = useProxyStore((state) => state.currentProxy);
  const { setFirstProxy } = useProxy(open);

  useEffect(() => {
    function handleMessage(message: MessageEvent<OpenTemuDialogMessage>) {
      if (message.data.type === PostMessageType.openTemuDialog) {
        setOpen(true);
      }
    }
    window.addEventListener('message', handleMessage);

    return () => {
      window.removeEventListener('message', handleMessage);
    };
  }, []);

  useEffect(() => {
    if (!open) {
      window.parent.postMessage(
        {
          type: PostMessageType.closeTemuDialog,
        },
        'https://seller.kuajingmaihuo.com/',
      );
    }
  }, [open]);

  useEffect(() => {
    if (open) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = 'auto';
    }
  }, [open]);

  // 每隔一小时刷新 https://seller.kuajingmaihuo.com/ 和 https://agentseller.temu.com/ 两个网站
  useEffect(() => {
    const interval = setInterval(
      () => {
        try {
          fetch(`https://seller.kuajingmaihuo.com/`);
          fetch(`https://agentseller.temu.com/`);
        } catch (error) {
          console.log(error);
        }
      },
      60 * 60 * 1000,
    );
    return () => clearInterval(interval);
  }, []);

  return (
    <div>
      <Dialog open={open} onOpenChange={setOpen} modal={false}>
        <DialogContent
          onPointerDownOutside={(e) => e.preventDefault()}
          aria-describedby=""
          className="w-[90%] max-w-[1500px] h-[90vh] grid-rows-[auto_1fr]"
          style={{
            outline: `${open ? '9000px solid #000000e0' : 'none'}`,
            zIndex: config.dialogZIndex,
          }}
        >
          <DialogHeader>
            <div className="flex items-center">
              <DialogTitle className="text-card-foreground/80 flex items-center grow">
                <div>temu 自动化处理</div>
                <Button
                  onClick={async () => {
                    await setProxyDirect();
                    proxyDispatch({
                      type: 'update',
                      update(state) {
                        state.currentProxy = config.proxyDirectLabel;
                      },
                    });
                  }}
                  size={'sm'}
                  className="hover:bg-[#337AB7] bg-[#428BCA] mr-3 ml-auto"
                >
                  切换直连
                </Button>
                <Button
                  onClick={async () => {
                    await setFirstProxy();
                  }}
                  size={'sm'}
                  className="hover:bg-[#337AB7] bg-[#428BCA] mr-3"
                >
                  切换代理({currentProxy})
                </Button>
              </DialogTitle>
            </div>
          </DialogHeader>
          <div className="flex">
            <OperationType></OperationType>

            <Tabs value={currentTabValue} className="flex flex-col grow">
              {temuOperationList.map((operationItem) => {
                return (
                  <TabsContent
                    key={operationItem.label}
                    value={operationItem.label}
                    className="grow flex flex-col data-[state=inactive]:hidden mt-0"
                  >
                    <Card className="grow flex flex-col relative">
                      <CardContent className="space-y-2 grow flex flex-col mt-1">
                        {operationItem.label === '同步库存' ? (
                          <AvaliableSynchronization className="grow" />
                        ) : null}
                        {operationItem.label === '报名活动' ? (
                          <RegidtrationActivity className="grow" />
                        ) : null}
                      </CardContent>
                    </Card>
                  </TabsContent>
                );
              })}
              <TabsContent
                value={config.temuAvailableSettingsTabValue}
                className="grow flex flex-col data-[state=inactive]:hidden mt-0"
              >
                <Card className="grow flex flex-col relative">
                  <CardContent className="space-y-2 grow flex flex-col p-1">
                    <TemuSetting className="flex flex-col grow"></TemuSetting>
                  </CardContent>
                </Card>
              </TabsContent>
            </Tabs>
          </div>
        </DialogContent>
      </Dialog>
      <Toaster className="[&_li]:p-4"></Toaster>
    </div>
  );
}

export default App;
